package com.ray.aopdemo.aopdemo1;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * User: Ray.Shaw <p />
 * Time: 2019/11/1 14:34  <p />
 * Version: V1.0  <p />
 * Description: https://www.jianshu.com/p/aaeb2355ec5c <p />
 */
public class TestProxyAop {
    public static void main(String[] args) {
//        Waiter waiter = new ManWaiter();
//        waiter.server();

        new TestProxyAop().test();
    }

    public void test() {
        Waiter manWaiter = new ManWaiter();
        ClassLoader classLoader = this.getClass().getClassLoader();
        Class[] interfaces = {Waiter.class};
        InvocationHandler invocationHandler = new WaiterInvocationHandler(manWaiter);
        //得到代理对象，代理对象就是在目标对象的基础上进行了增强的对象
        Waiter waiter = (Waiter) Proxy.newProxyInstance(classLoader, interfaces, invocationHandler);
        waiter.server();//前面添加“你好”，后面添加“再见”
    }
}

class WaiterInvocationHandler implements InvocationHandler {
    private Waiter waiter;

    WaiterInvocationHandler(Waiter waiter) {
        this.waiter = waiter;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("你好");
        waiter.server();//调用目标对象的方法
        System.out.println("再见");
        return null;
    }
}
